-- read a text and 
-- 1. calculate the number of occurrences for each word
-- 2. sort the word list by number of occurrences
-- 3. output the first n elements

local counter = {}

for line in io.lines() do
	for word in string.gmatch(line, "%w+") do
		counter[word] = (counter[word] or 0) + 1
	end
end

local words = {}

for w in pairs(counter) do
	words[#words + 1] = w
end

table.sort(words, function (w1, w2)
	return counter[w1] > counter[w2] or
				 counter[w1] == counter[w2] and w1 < w2
end)

local n = math.min(tonumber(arg[1]) or math.huge, #words)

for i = 1, n do
	io.write(words[i], "\t", counter[words[i]], "\n")
end

